package net.dgg.rz.common.xssFilter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class MyRequestWrapper extends HttpServletRequestWrapper {
    public MyRequestWrapper(HttpServletRequest request) {
        super(request);
    }
    @Override
    public String[] getParameterValues(String name) {
        String[] values =super.getParameterValues(name);
        if(values==null) {
            return values;
        }
        String[] vals = getNewValus(values);
        if(vals!=null&&vals.length==0) {
            vals = values;
        }
        return vals;
    }


    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> parameterMap = super.getParameterMap();
        Map<String, String[]> newparameterMap = new HashMap<String, String[]>();
        Set<String> keys = parameterMap.keySet();
        for (String param : keys) {
            String[] values = parameterMap.get(param);
            String[] newValus = getNewValus(values);
            newparameterMap.put(param, newValus);
        }
        return newparameterMap;
    }


    private String[] getNewValus(String[] values) {
        String[] vals= new String[values.length];
        if(values!=null){
            for (int i = 0; i < values.length; i++) {
                String value=values[i];
                String escapeJava = filtertText(value);
                vals[i]=escapeJava;
            }
        }
        return vals;
    }
    private String filtertText(String value) {
        if(StringUtils.isBlank(value)){
            return value;
        }
        value = clearXss(value);
        return value;
    }

    // 清除路径中的转义字符
    public String clearXss(String value) {

        if (value == null || "".equals(value)) {
            return value;
        }
        value = value.replaceAll("<", "&lt;").replaceAll(">", "&gt;");
        /*value = value.replaceAll("\\(", "&#40;").replace("\\)", "&#41;");*/
        value = value.replaceAll("'", "&#39;");
        value = value.replaceAll("eval\\((.*)\\)", "");
        value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']",
                "\"\"");
        value = value.replace("script", "");

        return value;
    }

}
